﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using DatabaseLayer;

namespace AudioToVideoConversion
{
    public class AudioToVideo
    {
        private String sSource = "Audio To Video Conversion";
        private String sLog = "Application";

        public AudioToVideo()
        {
            if (!EventLog.SourceExists(sSource))
                EventLog.CreateEventSource(sSource, sLog);
            EventLog.WriteEntry(sSource, "Constructor Started");
        }

        public bool convertAudioFiletoVideoFile(string audioInputFileLocation, string imageToBeUsedInVideo, string outputVideoFile)
        {
            bool statusMessageConversion = true;

            DatabaseFunctions objectDatabaseFunctions = new DatabaseFunctions();
            var configurationData = objectDatabaseFunctions.getIVRJunctionConfiguration();

            String programFolder = configurationData.Item2;

            String folderPath = Path.GetDirectoryName(audioInputFileLocation);
            String fileName = Path.GetFileName(audioInputFileLocation);
            String fileNameWithoutExtension = Path.GetFileNameWithoutExtension(audioInputFileLocation);
            
            String strCmdTxt = "/c cd "+programFolder+"\\sox-14-4-0 & sox " + audioInputFileLocation + " -n stat -v";

            ProcessStartInfo i = new ProcessStartInfo("cmd.exe", strCmdTxt);
            i.CreateNoWindow = true;
            i.RedirectStandardOutput = true;
            i.RedirectStandardError = true;
            i.UseShellExecute = false;

            Process p = new Process();
            p.StartInfo = i;
            p.Start();

            var result = p.StandardOutput.ReadToEnd();
            String error = p.StandardError.ReadToEnd();

            bool exceptionOccured = false;

            double volume = 0;
            try
            {
                volume = Convert.ToDouble(error);
            }
            catch (FormatException formatException)
            {
                exceptionOccured = true;
                // Add the event logger
            }

            p.WaitForExit();
            EventLog.WriteEntry(sSource, "Volume permissible enhancement limit obtained", EventLogEntryType.Information);
            p.Close();

            if (!exceptionOccured)
            {
                strCmdTxt = "/c cd "+programFolder+"\\sox-14-4-0 & sox " + audioInputFileLocation + " -r 8000 -t wav -c 1 " + folderPath + "\\" + fileNameWithoutExtension + "Temp.wav vol " + volume;
                //strCmdTxt = "/c cd C:\\ffmpeg & ffmpeg -i importantnew.wav -i image.jpg important.mkv";
                i = new ProcessStartInfo("cmd.exe", strCmdTxt);
                i.CreateNoWindow = true;
                i.RedirectStandardOutput = true;
                i.RedirectStandardError = true;
                i.UseShellExecute = false;

                p = new Process();
                p.StartInfo = i;
                p.Start();

                result = p.StandardOutput.ReadToEnd();
                error = p.StandardError.ReadToEnd();

                p.WaitForExit();
                EventLog.WriteEntry(sSource, "Volume amplified", EventLogEntryType.Information);
                p.Close();

                try
                {
                    System.IO.File.Replace(folderPath + "\\" + fileNameWithoutExtension + "Temp.wav", audioInputFileLocation,
                        folderPath + "\\" + fileNameWithoutExtension + "Backup.wav");
                    System.IO.File.Delete(fileNameWithoutExtension + "Temp.wav");
                    System.IO.File.Delete(fileNameWithoutExtension + "Backup.wav");
                    
                    EventLog.WriteEntry(sSource, "Amplified files replaces the original audio files", EventLogEntryType.Information);
                
                }
                catch (Exception generalException)
                {
                    EventLog.WriteEntry(sSource, "Error in replacing the modified files:"+generalException.Message, EventLogEntryType.Error);
                }
            }

            // convert the audio to video
            //strCmdTxt = "/c cd C:\\ffmpeg & ffmpeg -i "+filePath+" -i "+imagePath+" -acodec copy -vcodec mjpeg "+outputVideoFilePath;
            strCmdTxt = "/c cd "+programFolder+"\\ffmpeg\\bin & ffmpeg -i " + audioInputFileLocation + "  -loop 1 -i " + imageToBeUsedInVideo + " -r 1 -ab 128k -acodec copy -vcodec mpeg4 -y -shortest " + outputVideoFile;

            i = new ProcessStartInfo("cmd.exe", strCmdTxt);
            i.CreateNoWindow = true;
            i.UseShellExecute = false;
            p = new Process();
            p.StartInfo = i;
            p.Start();

            p.WaitForExit();
            EventLog.WriteEntry(sSource, "Audio To Video Conversion Successful", EventLogEntryType.Information);                
            p.Close();

            statusMessageConversion = File.Exists(outputVideoFile);

            return statusMessageConversion;
        }
    }
}